package test;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.Writer;
import java.sql.*;

public class LoginServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request,
                          HttpServletResponse response) throws ServletException, IOException {
        System.out.println("do post");
        //表单数据
        //account: input name
        //password :input name

        String account = request.getParameter("account");
        String password = request.getParameter("password");
        System.out.println(account+":"+password);
        //可以获取前台页面发送的数据（请求中的数据）、
//        if(account.equals("admin")&&password.equals("12346")){
        //设置仙姑的回去的内容是什么
        response.setContentType("text/plain;charset=utf8");
//        response.setContentType("text/html;charset=utf8");
        //设置响应的编码
        response.setCharacterEncoding("utf-8");
        if(isLogin(account,password)){
            //如何输出数据到网页上呢
//            Writer w = response.getWriter();//获取一个流
//            w.write("<div style='color:blue'>成功</div>");
//            response.sendRedirect("http://localhost/success.html");//重定向 一行
            //在传递这一次  中转站 全篇
           request.getRequestDispatcher("success.html").forward(request,response);
        }

        else{
            request.getRequestDispatcher("error.html").forward(request,response);

//            Writer w = response.getWriter();//获取一个流
//            w.write("<div style='color:red'>失败</div>");
//            response.sendRedirect("http://localhost/error.html");//重定向

        }
    }

    private boolean isLogin(String account, String password) {
        try{
            //1、初始化一些配置信息
            Class.forName("com.mysql.cj.jdbc.Driver");
            //2、连接数据库的动作
            String url="jdbc:mysql://localhost:3306/demotest01 ?characterEncoding=UTF-8&serverTimezone=GMT%2B8";//数据库的地址
            String mysqlUser="root";//数据账号：root
            String mysqlPsd="root";//数据库密码：root
            Connection conn = DriverManager.getConnection(url, mysqlUser, mysqlPsd);//连接

            Statement statement = conn.createStatement();//静态
            String sql="select * from user where account='"+account+"'and password='"+password+"'";
            ResultSet resultSet = statement.executeQuery(sql);//查询
            boolean ok =resultSet.next();//有下一个元素，有的话表示找到该用户
                    //记得关闭：最后使用的内容先关闭
            resultSet.close();
            statement.close();
            conn.close();
            return ok;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return true;
    }
    //true 表示账号密码验证成功

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        System.out.println("do get");
    }
}
